package com.chinasoftinc.facommon.view.device;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.ace.ability.AceAbility;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.rpc.RemoteException;

import com.chinasoftinc.facommon.DeviceControlConstants;
import com.chinasoftinc.facommon.FAConfigMgr;
import com.chinasoftinc.facommon.control.service.HilinkDeviceServiceAbility;
import com.chinasoftinc.facommon.utils.LogUtil;
import com.chinasoftinc.facommon.view.BaseAceAbility;
import com.chinasoftinc.facommon.view.device.abilitypersent.BleDevicePresent;
import com.chinasoftinc.facommon.view.device.abilitypersent.DeviceAbilityPresent;
import com.chinasoftinc.facommon.view.device.abilitypersent.WifiDevicePresent;

/**
 * 连接控制设备页面
 *
 * @since 2022-05-13
 */
public class ControlDeviceAbility extends BaseAceAbility {
    private static final String TAG = "DeviceAbility";

    private static final int HALF_MODAL = 1;
    private DeviceAbilityPresent present;

    @Override
    public void onStart(Intent intent) {
        intent.setParam("window_modal", HALF_MODAL);
        present = FAConfigMgr.get().isBleMode() ? new BleDevicePresent(this) : new WifiDevicePresent(this);
        present.onStart(intent);
        super.onStart(intent);
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        present.onNewIntent(intent);
    }

    @Override
    public void onActive() {
        super.onActive();
        publishCloseFaEvent();
    }

    @Override
    public void onStop() {
        present.onStop();
        super.onStop();
    }

    private void publishCloseFaEvent() {
        try {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                .withAction(DeviceControlConstants.ACTION_CLOSE)
                .build();
            intent.setOperation(operation);
            CommonEventData eventData = new CommonEventData(intent);
            CommonEventManager.publishCommonEvent(eventData);
            LogUtil.info(TAG, "Publish succeeded");
        } catch (RemoteException e) {
            LogUtil.error(TAG, "Exception occurred during publishCommonEvent invocation");
        }
    }
}
